/**
 * 
 */
package com.manthano.util.event.queue;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;

import org.apache.log4j.Logger;

/**
 * @author Dell
 */
public class EventQueueSubscriber implements MessageListener
{
	private static final Logger		logger			= Logger.getLogger(EventQueueSubscriber.class);

	private Set<EventQueueListener>	queueListeners	= new LinkedHashSet<EventQueueListener>();

	/**
	 * @return the queueListeners
	 */
	public Set<EventQueueListener> getQueueListeners()
	{
		return queueListeners;
	}

	/**
	 * @param queueListeners
	 *            the queueListeners to set
	 */
	public void setQueueListeners(Set<EventQueueListener> queueListeners)
	{
		this.queueListeners = queueListeners;
	}

	@Override
	public void onMessage(Message message)
	{
		try
		{
			if (message instanceof ObjectMessage)
			{

				handleEventMessage(message);
			}
		}
		catch (JMSException e)
		{
			logger.error("Error in onMessage() of" + EventQueueSubscriber.class.getName() + e);
		}
	}

	private void handleEventMessage(Message objectMessage) throws JMSException
	{
		MultiEventObject multiEventObject = (MultiEventObject) ((ObjectMessage) objectMessage).getObject();
		for (EventQueueListener eventQueueListener : getQueueListeners())
		{
			try
			{
				eventQueueListener.handleEvent(multiEventObject);
			}
			catch (Exception e)
			{
				Queue queue = (Queue) objectMessage.getJMSDestination();
				logger.error("Error in handle event for Queue:" + queue.getQueueName() + " MultiEventObject:"
						+ eventQueueListener, e);
			}
		}
	}
}
